package gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import data.DepartmentData;
import data.GetOrderListResponse;
import data.Order;


public class OrderListDialog extends JDialog implements ActionListener {
	private static final long serialVersionUID = 6042423806077133648L;
	private final JPanel contentPanel = new JPanel();
	private JTree mTree;
	private Order mDialogResponse = null;
	
	private final static String CANCEL_COMMAND = "Cancel";
	private final static String OK_COMMAND = "Ok";
	
	public OrderListDialog(final GetOrderListResponse orderList, final Map<Integer, DepartmentData> departments) {
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setPreferredSize(new Dimension(300, 300));
		setTitle("Wyb\u00f3r zam\u00f3wienia");
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));

		JLabel lblNewLabel = new JLabel("Wybierz zam\u00F3wienie do otworzenia:");
		lblNewLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		contentPanel.add(lblNewLabel, BorderLayout.NORTH);

		mTree = new JTree();
		mTree.setScrollsOnExpand(true);
		mTree.setShowsRootHandles(true);
		mTree.setRootVisible(false);
		mTree.setCellRenderer(new MyRenderer());
		mTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("root") {
			private static final long serialVersionUID = 7417934389311945008L;

			{
				DefaultMutableTreeNode node;
				DefaultMutableTreeNode departmentsNode;
				DefaultMutableTreeNode costUnitNode;
				DefaultMutableTreeNode dateNode;
				DefaultMutableTreeNode paymentMethodNode;
				for (Order order : orderList.getOrders()) {
					node = new DefaultMutableTreeNode(order);
					costUnitNode = new DefaultMutableTreeNode("Jednostka kosztowa: " + order.getCostUnit());
					dateNode = new DefaultMutableTreeNode("Data: " + new SimpleDateFormat("yyyy-MM-DD").format(order.getDate()));
					paymentMethodNode = new DefaultMutableTreeNode("Metoda p\u0142atno\u015bci: " + (order.getPaymentMethod() == 1 ? "przelew" : "got\u00f3wka"));
					departmentsNode = new DefaultMutableTreeNode("Obiekty");
					for (DepartmentData department : order.getOrderDepartments().keySet()) {
						DepartmentData tmp = departments.get(department.getId());
						if (tmp != null)
							departmentsNode.add(new DefaultMutableTreeNode(tmp.getName()));
					}
					node.add(costUnitNode);
					node.add(dateNode);
					node.add(paymentMethodNode);
					node.add(departmentsNode);
					add(node);
				}
			}
		}));
		JScrollPane qPane = new JScrollPane(mTree,
			      JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
			      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		contentPanel.add(qPane, BorderLayout.CENTER);
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
		getContentPane().add(buttonPane, BorderLayout.SOUTH);
		
		JButton okButton = new JButton("OK");
		okButton.setActionCommand(OK_COMMAND);
		okButton.addActionListener(this);
		buttonPane.add(okButton);
		getRootPane().setDefaultButton(okButton);
		JButton cancelButton = new JButton("Anuluj");
		cancelButton.setActionCommand(CANCEL_COMMAND);
		cancelButton.addActionListener(this);
		buttonPane.add(cancelButton);
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		if (evt.getActionCommand() == OK_COMMAND) {
			TreePath path = mTree.getSelectionPath();
			if (path == null) {
				JOptionPane.showMessageDialog(OrderListDialog.this, "Musisz najpierw zaznaczy\u0107 zam\u00f3wienie, kt\u00f3re chcesz otworzy\u0107.");
				return;
			} else if (path.getPathCount() == 3) { //Zaznaczona w�a�ciwo��
				path = path.getParentPath();
			} else if (path.getPathCount() == 4) { //Zaznaczony departament
				path = path.getParentPath().getParentPath();
			}
			mDialogResponse = (Order)((DefaultMutableTreeNode)path.getLastPathComponent()).getUserObject();
			OrderListDialog.this.dispose();
		} else if (evt.getActionCommand() == CANCEL_COMMAND) {
			OrderListDialog.this.dispose();
		}
	}

	public Order getDialogResponse() {
		return mDialogResponse;
	}
	
	class MyRenderer extends DefaultTreeCellRenderer {
		private static final long serialVersionUID = -4124389106546699276L;

		public Component getTreeCellRendererComponent(
	                        JTree tree,
	                        Object value,
	                        boolean sel,
	                        boolean expanded,
	                        boolean leaf,
	                        int row,
	                        boolean hasFocus) {

			if (value instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)value).getUserObject() instanceof Order) {
				Order order = (Order)((DefaultMutableTreeNode)value).getUserObject();
				value = order.getNumber() + " (" + order.getState().toString() + ")";
			}
	        super.getTreeCellRendererComponent(
	                        tree, value, sel,
	                        expanded, leaf, row,
	                        hasFocus);

	        return this;
	    }
	}
}
